//
//  main.swift
//  DMRConcurrency
//
//  Created by edy on 2025/9/30.
//

import Foundation

//print("Hello, World!")

test2()

Thread.sleep(forTimeInterval: 1)

func test2() {
    Task {
        let task = Task {
            print("task start")
            try await Task.sleep(nanoseconds: 10_000_000_000)
            try Task.checkCancellation()
            print("task finish, isCancelled: \(Task.isCancelled)")
        }
        
        try? await Task.sleep(nanoseconds: 500_000_000)
        task.cancel()
        
        print(await task.result)
    }
}



func helloAsync() async -> Int {
    //    await withCheckedContinuation { continuation in
    //        DispatchQueue.main.async {
    //            continuation.resume(returning: 100)
    //        }
    //    }
    let task = Task {
        return 1
    }
    return await task.value
}

func helloAsyncThrow() async throws -> Int  {
    try await withCheckedThrowingContinuation { continuation in
        DispatchQueue.main.async {
            continuation.resume(returning: 90)
        }
    }
}

func test1() {
    Task {
        Task {
            let ret = await helloAsync()
            print(ret)
            
            print("ccc")
        }
        
        Task {
            let ret2 = try await helloAsyncThrow()
            print(ret2)
            
            print("ddd")
            
            await MainActor.run {
                print("mmm")
            }
        }
        
        let ret = await helloAsync()
        print("aaa \(ret)")
        
        let ret2 = try await helloAsyncThrow()
        print("bbb \(ret)")
        
        try? await Task.sleep(nanoseconds: 1000 * 1000 * 1000)
    }
}
